package dry.example.gui;

import javax.swing.*;
import java.awt.*;

public class GridBagLayoutWithGridLines extends JPanel {
    private final int rows;
    private final int cols;
    private final int cellWidth;
    private final int cellHeight;

    public GridBagLayoutWithGridLines(int rows, int cols, int cellWidth, int cellHeight) {
        this.rows = rows;
        this.cols = cols;
        this.cellWidth = cellWidth;
        this.cellHeight = cellHeight;

        // 设置布局为 GridBagLayout
        setLayout(new GridBagLayout());

        GridBagConstraints gbc = new GridBagConstraints();

        // 添加示例组件
        for (int i = 0; i < rows * cols; i++) {
            JLabel label = new JLabel("Cell " + i);
            gbc.gridx = i % cols;
            gbc.gridy = i / cols;
            add(label, gbc);
        }
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);

        Graphics2D g2d = (Graphics2D) g;
        g2d.setColor(Color.LIGHT_GRAY);

        // 绘制行
        for (int row = 0; row <= rows; row++) {
            g2d.drawLine(0, row * cellHeight, getWidth(), row * cellHeight);
        }

        // 绘制列
        for (int col = 0; col <= cols; col++) {
            g2d.drawLine(col * cellWidth, 0, col * cellWidth, getHeight());
        }
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame("GridBagLayout with Grid Lines");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(600, 400);

        // 假设我们有一个 5x5 的网格，每个单元格大小为 100x30
        frame.add(new GridBagLayoutWithGridLines(5, 5, 100, 30));

        frame.setVisible(true);
    }
}
